package com.iflytek.cosmo.ocr.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.iflytek.cosmo.ocr.common.config.UapProperties;
import com.iflytek.cosmo.ocr.common.constant.UapConstant;
import com.iflytek.cosmo.ocr.common.json.Jackson;
import com.iflytek.cosmo.ocr.model.dto.AuthOutput;
import com.iflytek.cosmo.ocr.model.dto.ChangePwdParam;
import com.iflytek.cosmo.ocr.model.dto.UapApp;
import com.iflytek.cosmo.ocr.model.dto.UapAuth;
import com.iflytek.cosmo.ocr.model.dto.UapExtend;
import com.iflytek.cosmo.ocr.model.dto.UapOutput;
import com.iflytek.cosmo.ocr.model.dto.UapUser;
import com.iflytek.cosmo.ocr.model.dto.UapUserExtendDto;
import com.iflytek.cosmo.ocr.model.dto.UserAuthOutput;
import com.iflytek.cosmo.ocr.model.dto.UserOutput;
import com.iflytek.cosmo.ocr.service.UserInfoService;
import com.iflytek.cosmo.ocr.support.uap.UapClient;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * uap服务
 * @author yunsun
 *
 */
@Service("uap")
public class UapExtraServiceImpl implements UserInfoService {
	
	/**
	 * uap配置
	 */
	@Autowired
	private UapProperties uapProperties;
	
	/**
	 * RestTemplate
	 */
	@Autowired
	private RestTemplate restTemplate;

	/**
	 * UapClient
	 */
	@Autowired
	private UapClient uapClient;

	@Override
	public UserOutput getUserInfoById(String userId) {
		UserOutput userOutput = null;
		
		// 请求路径
		String requestUrl = uapProperties.getServerUrl() + "/rest/user/get/detail/byUserId?userId={userId}";

		Map<String, String> map = new HashMap<>();
		map.put("userId", userId);

		String json = restTemplate.getForObject(requestUrl, String.class, map);
		UapOutput<UapUserExtendDto> uapOutput = Jackson.parse2T(json, new TypeReference<UapOutput<UapUserExtendDto>>() {});
		if (uapOutput != null && uapOutput.getFlag()) {
			UapUserExtendDto uapUserExtendDto = uapOutput.getData();
			if (uapUserExtendDto != null) {
				UapUser uapUser = uapUserExtendDto.getUser();
				userOutput = new UserOutput(uapUser.getId(), uapUser.getName());
			}
		}

		return userOutput;
	}

	@Override
	public Boolean checkUser(String userName, String pwd) {
		Boolean flag = false;
		
		// 请求路径
		String requestUrl = uapProperties.getServerUrl() + "/rest/validate/loginByLoginNamePassWord/{loginName}/{passWord}";

		Map<String, String> map = new HashMap<>();
		map.put("loginName", userName);
		map.put("passWord", pwd);

		String json = restTemplate.getForObject(requestUrl, String.class, map);
		UapOutput<UapUser> uapOutput = Jackson.parse2T(json, new TypeReference<UapOutput<UapUser>>() {});
		
		if(uapOutput != null){
			flag = uapOutput.getFlag();
		}

		return flag;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public UapOutput<String> registerUser(String userName, String pwd) {

		//组装uap用户对象
		UapUserExtendDto uapUserExtendDto = formRegisterUapUserInfo(userName, pwd);
		UapOutput<String> uapOutput = uapClient.registerUser(uapUserExtendDto);

		if (uapOutput == null) {
			return null;
		}
		if (!uapOutput.getFlag()) {
			return uapOutput;
		}
		//注册成功修改默认密码

		if (!pwd.equals(uapProperties.getUserDefaultPwd())) {
			//获取默认密码
			String defaultPwd = uapProperties.getUserDefaultPwd();
			//base64 旧密码（默认密码）
			String oldPwd = new String(Base64.encodeBase64(defaultPwd.getBytes()));
			//base64 新密码（页面输入）
			String newPwd = new String(Base64.encodeBase64(pwd.getBytes()));

			UapOutput result = uapClient.changePwd(userName, oldPwd, newPwd);
			if (result == null) {
				return null;
			}
			if (!result.getFlag()) {
				return result;
			}
		}

		uapClient.userBindGroup(uapProperties.getGroupCode(), uapOutput.getData());
		uapClient.userBindRole(uapOutput.getData(), uapProperties.getUserRole());

		return uapOutput;
	}
	
	/**
	 * 组装uap用户对象
	 * @param userName 用户登录名
	 * @param pwd 密码
	 * @return uap用户对象
	 */
	private UapUserExtendDto formRegisterUapUserInfo(String userName, String pwd) {
		UapUserExtendDto uapUserExtendDto = new UapUserExtendDto();

		//用户基本信息
		UapUser uapUser = new UapUser();
		uapUser.setLoginName(userName);
		uapUser.setName(userName);
		uapUser.setOrgId(uapProperties.getUserOrgId());
		uapUser.setOrgName(uapProperties.getUserOrgName());
		uapUser.setUserSource(UapConstant.USER_SOURCE_SYSTEM);
		uapUser.setUserType(UapConstant.USER_TYPE_NORMAL);
		uapUser.setStatus(UapConstant.USER_STATUS_UNDELETED);
		//设置用户基本信息
		uapUserExtendDto.setUser(uapUser);
		
		// 获取扩展字典 请求路径
		String requestUrl = uapProperties.getServerUrl() + "/rest/extend/userExtend";
		
		String json = restTemplate.getForObject(requestUrl, String.class);
		UapOutput<List<UapExtend>> uapOutput = Jackson.parse2T(json, new TypeReference<UapOutput<List<UapExtend>>>() {});
		
		List<UapExtend> resultList = new ArrayList<UapExtend>();
		if(uapOutput != null){
			List<UapExtend> uapExtendList = uapOutput.getData();
			if(uapExtendList != null && uapExtendList.size() > 0){

				//分析扩展信息字段
				for (UapExtend uapExtend : uapExtendList) {
					
					String nameCode = uapExtend.getNameCode();
					//department设置成“法院”；enable设置成 1；登录次数loginCount设置成 0；picUrl设置成 -1
					if(UapConstant.EXTEND_DEPT_PROP.equals(nameCode) || UapConstant.EXTEND_ENABLE_PROP.equals(nameCode)
							|| UapConstant.EXTEND_PICURL_PROP.equals(nameCode) || UapConstant.EXTEND_LOGCOUNT_PROP.equals(nameCode)){
						UapExtend result = new UapExtend();
						result.setId(uapExtend.getId());
						result.setName(uapExtend.getName());
						result.setNameCode(uapExtend.getName());
						result.setMandatory(UapConstant.MANDATORY_YES);
						if(UapConstant.EXTEND_DEPT_PROP.equals(nameCode)){
							result.setValue(UapConstant.EXTEND_DEPT_DEFAULT);
						}
						if(UapConstant.EXTEND_ENABLE_PROP.equals(nameCode)){
							result.setValue(UapConstant.EXTEND_ENABLE_DEFAULT);
						}
						if(UapConstant.EXTEND_PICURL_PROP.equals(nameCode)){
							result.setValue(UapConstant.EXTEND_PICURL_DEFAULT);
						}
						if(UapConstant.EXTEND_LOGCOUNT_PROP.equals(nameCode)){
							result.setValue(UapConstant.EXTEND_LOGCOUNT_DEFAULT);
						}
						resultList.add(result);
					}
				}
			}
		}
		//设置用户扩展信息
		uapUserExtendDto.setExtands(resultList);
		
		return uapUserExtendDto;
	}

	@Override
	public UserOutput getUserInfoByName(String userName) {
		UserOutput userOutput = null;
		
		// 检查参数是否为mac地址格式
		boolean flag = checkMacAddress(userName);

        //在uap中查询
        UapUser uapUser = uapClient.getUserByLoginName(userName);
        if (uapUser != null) {
            userOutput = new UserOutput(uapUser.getId(), uapUser.getName());
        }

		return userOutput;
	}

	@Override
	public Map<String, Object> checkAndGetUserInfo(String userName, String pwd) {
		Map<String, Object> result = new HashMap<String, Object>();

		Boolean flag = false;
		String message = "";
		UserAuthOutput userAuthOutput = null;

		UapOutput<UapUser> uapOutput = uapClient.loginByLoginNamePassWord(userName, pwd);

		if (uapOutput != null) {
			flag = uapOutput.getFlag();
			message = uapOutput.getMessage();
			if(flag){
				UapUser uapUser = uapOutput.getData();
				userAuthOutput = new UserAuthOutput(uapUser.getId(), uapUser.getLoginName(), uapUser.getName(), getAuthByUserId(uapUser.getId()));
			}
		}
		
		result.put("isValid", flag);
		result.put("message", message);
		result.put("userInfo", userAuthOutput);

		return result;
	}
	
	/**
	 * 检查参数是否为mac地址格式
	 * @param str 参数
	 * @return 是否为mac地址格式
	 */
	private boolean checkMacAddress(String str){
		if (str == null || "".equals(str)) {
		    return false;
        }
		return str.matches("^[A-F0-9]{2}(-[A-F0-9]{2}){5}$");
	}

	/**
	 * 修改密码
	 * @param changePwdParam 修改密码信息
	 * @return UapOutput
	 */
	@Override
	public UapOutput changePwd(ChangePwdParam changePwdParam) {
		return uapClient.changePwd(changePwdParam.getLoginName(), changePwdParam.getOldPwd(), changePwdParam.getNewPwd());
	}

	/**
	 * 用户验证
	 * @param userName 用户登录名
	 * @return 用户信息以及权限列表
	 */
	@Override
	public UserAuthOutput userCheck(String userName) {
		UapUser uapUser = uapClient.getUserByLoginName(userName);
		if (uapUser == null) {
			uapUser = new UapUser();
			UapUserExtendDto uapUserExtendDto = formRegisterUapUserInfo(userName, uapProperties.getUserDefaultPwd());
			UapOutput<String> uapOutput = uapClient.registerUser(uapUserExtendDto);
			if (uapOutput == null || !uapOutput.getFlag() || uapOutput.getData() == null || "".equals(uapOutput.getData())) {
				return null;
			}
			uapUser.setId(uapOutput.getData());
			uapUser.setLoginName(userName);
			uapClient.userBindRole(uapOutput.getData(), uapProperties.getVisitorRole());
		}
		return new UserAuthOutput(uapUser.getId(), uapUser.getLoginName(), uapUser.getName(), getAuthByUserId(uapUser.getId()));
	}

	/**
	 * 根据用户ID查询功能列表
	 * @param userId 用户ID
	 * @return 功能列表
	 */
	private List<AuthOutput> getAuthByUserId(String userId) {
		List<AuthOutput> authOutputs = new ArrayList<AuthOutput>();
		UapApp uapApp = uapClient.getAppByCode(uapProperties.getAppCode());
		if (uapApp == null) {
			return authOutputs;
		}
		List<UapAuth> uapAuths = uapClient.getAuthByAppIdUserId(uapApp.getId(), userId);
		if (uapAuths == null) {
			return authOutputs;
		}
		for (UapAuth uapAuth: uapAuths) {
			if (uapAuth.getUrl() == null) {
				continue;
			}
			AuthOutput authOutput = new AuthOutput(uapAuth.getId(), uapAuth.getName(), uapAuth.getUrl());
			authOutputs.add(authOutput);
		}
		return authOutputs;
	}
}
